package org.corey.share.db.dao;

import javax.persistence.Query;

import org.corey.share.db.entity.Article;
import org.corey.share.db.entity.Comment;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class CommentDaoImpl extends DefaultBaseDao implements CommentDao {

	public boolean addComment(Article a, Comment c) {
		a.getComments().add(c);
		this.save(c);
		this.update(a);
		return true;
	}

	public boolean deleteComment(Comment comment) {
		this.remove(comment);
		return true;
	}

	public boolean deleteComment(Long commentId) {
		Comment c = this.getCommentById(commentId);
		this.remove(c);
		return true;
	}

	public Comment getCommentById(Long commentId) {
		Key key = KeyFactory
				.createKey(Comment.class.getSimpleName(), commentId);
		Query query = getEM().createQuery("SELECT FROM Comment c WHERE c.key=?key");
		query.setParameter("key", key);
		Comment c = (Comment) query.getSingleResult();
		return c;
	}

}
